package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.resource.OperatorUserSystem;
import com.ruoyi.common.core.resource.OperatorUserSystemHolder;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @Description:
 * @Company: 北京卡拉卡尔股份技术有限公司
 * @Author: Darren Ho
 * @Date: 10/9/2020 18:01
 */
@Service("userDetailsServiceDelegator")
public class UserDetailsServiceDelegator implements UserDetailsService {

    private final static String USER_DETAILS_SERVICE_BEAN_NAME_SUFFIX = UserDetailsService.class.getSimpleName();

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        return getUserDetailsService().loadUserByUsername(username);
    }

    private UserDetailsService getUserDetailsService() {
        OperatorUserSystem operatorUserSystem = OperatorUserSystemHolder.get();
        Assert.notNull(operatorUserSystem, "Only non-null operator user system  is permitted");
        String prefix = StringUtils.substringBefore(operatorUserSystem.name().toLowerCase(), "_");
        String beanName = prefix + USER_DETAILS_SERVICE_BEAN_NAME_SUFFIX;
        Object bean = SpringUtils.getBean(beanName);
        if (bean == null) {
            String message = String.format("name[%s]的bean 未注册,不存在", beanName);
            throw new CustomException(message);
        }
        return (UserDetailsService) bean;
    }
}
